/*
 * Copyright (c) 2025 CAX Conversion Project
 */
package com.comac.ins.cax.service.impl;

import cn.hutool.core.lang.Dict;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.comac.ins.cax.domain.CaxFileInfo;
import com.comac.ins.cax.domain.bo.CaxFileInfoBo;
import com.comac.ins.cax.domain.bo.CaxSysLogBo;
import com.comac.ins.cax.domain.vo.CaxConvertInfoVo;
import com.comac.ins.cax.domain.vo.CaxFileInfoExportVo;
import com.comac.ins.cax.domain.vo.CaxSysLogVo;
import com.comac.ins.cax.enums.CaxConstants;
import com.comac.ins.cax.enums.CaxConvertStatus;
import com.comac.ins.cax.enums.CaxConvertType;
import com.comac.ins.cax.service.ICaxSysLogService;
import com.comac.ins.common.core.utils.DateUtils;
import com.comac.ins.common.core.utils.StringUtils;
import com.comac.ins.common.excel.utils.ExcelUtil;
import com.comac.ins.common.json.utils.JsonUtils;
import com.comac.ins.common.log.enums.BusinessStatus;
import com.comac.ins.common.mybatis.core.page.PageQuery;
import com.comac.ins.common.mybatis.core.page.TableDataInfo;
import com.comac.ins.system.domain.SysOperLog;
import com.comac.ins.system.domain.vo.SysOperLogVo;
import com.comac.ins.system.mapper.SysOperLogMapper;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CaxSysLogServiceImpl implements ICaxSysLogService {
    @Autowired
    private  SysOperLogMapper sysOperLogMapper;

    @Override
    public TableDataInfo<CaxSysLogVo> selectList(CaxSysLogBo bo) {
        bo.setEndCreateTime(DateUtils.toOneDayEndTime(bo.getEndCreateTime()));
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        LambdaQueryWrapper<SysOperLog> lqw = this.buildQueryWrapper(bo);
        IPage<SysOperLogVo> sysOperLogVoIPage = sysOperLogMapper.selectVoPage(pageQuery.build(), lqw);
        List<SysOperLogVo> records = sysOperLogVoIPage.getRecords();

        List<CaxSysLogVo> caxSysLogVoList = this.handleList(records);
        Page<CaxSysLogVo> result = new Page<>();
        BeanUtils.copyProperties(sysOperLogVoIPage,result);
        result.setRecords(caxSysLogVoList);
        return TableDataInfo.build(result);
    }

    @Override
    public void export(HttpServletResponse response, CaxSysLogBo bo) {
        bo.setEndCreateTime(DateUtils.toOneDayEndTime(bo.getEndCreateTime()));
        LambdaQueryWrapper<SysOperLog> lqw = this.buildQueryWrapper(bo);
        List<SysOperLogVo> sysOperLogs = sysOperLogMapper.selectVoList(lqw);

        List<CaxSysLogVo> result = this.handleList(sysOperLogs);

        // 封装导出的data
        Map<String, Object> data = new HashMap<>();
        String fileName = "系统日志清单";
        data.put(fileName, result);
        ExcelUtil.exportWithOutTemplateMultiList(data, fileName, CaxSysLogVo.class, response);
    }

    private LambdaQueryWrapper<SysOperLog> buildQueryWrapper(CaxSysLogBo bo) {
        LambdaQueryWrapper<SysOperLog> lqw = Wrappers.lambdaQuery();
        lqw.eq(SysOperLog::getStatus, BusinessStatus.SUCCESS.ordinal());
        //格式转换：条件组装
        if (StringUtils.isNotEmpty(bo.getTitle()) && bo.getTitle().contains(CaxConstants.MODULE_CONVERT)){
            lqw.eq(StringUtils.isNotEmpty(bo.getTitle()),SysOperLog::getTitle,CaxConstants.MODULE_CONVERT);

            String convertType = bo.getTitle().replace(CaxConstants.MODULE_CONVERT, "");
            lqw.like(SysOperLog::getOperParam,convertType);
        }else {
            lqw.eq(StringUtils.isNotEmpty(bo.getTitle()),SysOperLog::getTitle,bo.getTitle());
        }
        lqw.eq(StringUtils.isNotBlank(bo.getBusinessType()), SysOperLog::getBusinessType, bo.getBusinessType());
        lqw.like(StringUtils.isNotBlank(bo.getOperName()), SysOperLog::getOperName, bo.getOperName());
        lqw.between(ObjectUtils.isNotEmpty(bo.getBeginCreateTime()) && ObjectUtils.isNotEmpty(bo.getEndCreateTime()),
                SysOperLog::getOperTime, bo.getBeginCreateTime(), bo.getEndCreateTime());
        lqw.orderByDesc(SysOperLog::getOperTime);
        return lqw;
    }

    /**
     * 处理列表数据
     * @param records
     * @return
     */
    private List<CaxSysLogVo> handleList(List<SysOperLogVo> records){
        List<CaxSysLogVo> caxSysLogVoList = new ArrayList<>();
        for (SysOperLogVo sysOperLogVo : records) {
            CaxSysLogVo caxSysLogVo = new CaxSysLogVo();
            BeanUtils.copyProperties(sysOperLogVo,caxSysLogVo);
            //处理模块名称
            if (CaxConstants.MODULE_CONVERT.equals(sysOperLogVo.getTitle())){
                if (sysOperLogVo.getOperParam().contains(CaxConvertType.CAD.toString())){
                    caxSysLogVo.setTitle(CaxConstants.MODULE_CAD_CONVERT);
                }
                if (sysOperLogVo.getOperParam().contains(CaxConvertType.CAE_INPUT.toString())){
                    caxSysLogVo.setTitle(CaxConstants.MODULE_CAE_INPUT_CONVERT);
                }
                if (sysOperLogVo.getOperParam().contains(CaxConvertType.CAE_OUTPUT.toString())){
                    caxSysLogVo.setTitle(CaxConstants.MODULE_CAE_OUTPUT_CONVERT);
                }

                //处理转换状态
                Dict dict = JsonUtils.parseMap(sysOperLogVo.getJsonResult());
                Map returnMap = (Map) dict.get("data");
                if (ObjectUtils.isEmpty(returnMap) || CaxConvertStatus.FAILURE.getCode().equals(returnMap.get("status"))){
                    caxSysLogVo.setOperStatus("失败");
                }
            }
            caxSysLogVoList.add(caxSysLogVo);
        }
        return caxSysLogVoList;
    }
}
